package com.weijian.service.impl;

import com.weijian.service.FileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 文件存储服务实现类
 */
@Slf4j
@Service
public class FileStorageServiceImpl implements FileStorageService {

    @Value("${file.storage.root:}")
    private String storageRoot;

    // 默认存储根目录
    private static final String DEFAULT_STORAGE_ROOT = "src/main/resources/cmake-build-debug/data";

    private static final String CSV_SUFFIX = ".csv";

    @Override
    public String saveCsvFile(MultipartFile file, Integer batchId, String fileType) throws IOException {
        // 验证文件
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 验证文件类型
        if (!StringUtils.hasText(fileType)) {
            throw new IllegalArgumentException("文件类型不能为空");
        }

        // 构建存储路径（从当前工作目录开始解析）
        String fileName = fileType + CSV_SUFFIX;
        Path batchDir = Paths.get("").toAbsolutePath()
                .resolve(getStorageRoot())
                .resolve(batchId.toString());
        Path targetPath = batchDir.resolve(fileName);

        // 创建目录
        if (!Files.exists(batchDir)) {
            Files.createDirectories(batchDir);
        }

        // 保存文件
        Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

        log.info("文件保存成功: batchId={}, fileType={}, path={}", batchId, fileType, targetPath);

        return targetPath.toString();
    }

    @Override
    public List<File> getFilesByBatchId(Integer batchId) {
        Path batchDir = Paths.get("").toAbsolutePath()
                .resolve(getStorageRoot())
                .resolve(batchId.toString());

        if (!Files.exists(batchDir)) {
            return new ArrayList<>();
        }

        List<File> files = new ArrayList<>();
        try {
            Files.list(batchDir)
                    .filter(Files::isRegularFile)
                    .forEach(path -> files.add(path.toFile()));
        } catch (IOException e) {
            log.error("获取批次文件列表失败: batchId={}", batchId, e);
        }

        return files;
    }

    @Override
    public File getFile(Integer batchId, String fileType) {
        Path filePath = Paths.get("").toAbsolutePath()
                .resolve(getStorageRoot())
                .resolve(batchId.toString())
                .resolve(fileType + CSV_SUFFIX);

        if (!Files.exists(filePath)) {
            return null;
        }

        return filePath.toFile();
    }

    @Override
    public String copyFileToDirectory(Integer batchId, String fileType, File targetDir) throws IOException {
        File sourceFile = getFile(batchId, fileType);

        if (sourceFile == null || !sourceFile.exists()) {
            throw new IOException(String.format("源文件不存在: batchId=%d, fileType=%s", batchId, fileType));
        }

        // 确保目标目录存在
        if (!targetDir.exists()) {
            Files.createDirectories(targetDir.toPath());
        }

        // 复制文件
        Path targetPath = targetDir.toPath().resolve(fileType + CSV_SUFFIX);
        Files.copy(sourceFile.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);

        log.info("文件复制成功: {} -> {}", sourceFile.getAbsolutePath(), targetPath);

        return targetPath.toString();
    }

    @Override
    public void copyAllFilesToDirectory(Integer batchId, File targetDir) throws IOException {
        List<File> files = getFilesByBatchId(batchId);

        if (files.isEmpty()) {
            log.warn("批次文件不存在: batchId={}", batchId);
            return;
        }

        // 确保目标目录存在
        if (!targetDir.exists()) {
            Files.createDirectories(targetDir.toPath());
        }

        // 复制所有文件
        for (File sourceFile : files) {
            String fileName = sourceFile.getName();
            Path targetPath = targetDir.toPath().resolve(fileName);
            Files.copy(sourceFile.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);
            log.debug("文件复制: {} -> {}", sourceFile.getAbsolutePath(), targetPath);
        }

        log.info("批次所有文件复制完成: batchId={}, targetDir={}, fileCount={}", batchId, targetDir, files.size());
    }

    @Override
    public void deleteBatchFiles(Integer batchId) {
        Path batchDir = Paths.get("").toAbsolutePath()
                .resolve(getStorageRoot())
                .resolve(batchId.toString());

        if (!Files.exists(batchDir)) {
            log.warn("批次目录不存在，无需删除: batchId={}", batchId);
            return;
        }

        try {
            // 删除目录及其所有内容
            Files.walk(batchDir)
                    .sorted((p1, p2) -> p2.getNameCount() - p1.getNameCount()) // 先删除子文件，再删除目录
                    .forEach(path -> {
                        try {
                            Files.delete(path);
                            log.debug("删除文件: {}", path);
                        } catch (IOException e) {
                            log.error("删除文件失败: {}", path, e);
                        }
                    });

            log.info("批次文件删除完成: batchId={}", batchId);
        } catch (IOException e) {
            log.error("删除批次文件失败: batchId={}", batchId, e);
        }
    }

    @Override
    public String getStorageRoot() {
        return StringUtils.hasText(storageRoot) ? storageRoot : DEFAULT_STORAGE_ROOT;
    }
}
